<template>
  <el-form>
    <el-form-item>
      <el-select v-model="roles" multiple placeholder="请选择">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button @click="submit">提交</el-button>
    </el-form-item>
  </el-form>
</template>
<script lang="ts">
import Vue from 'vue'
import { getUserRoles } from '@/services/user'
import { allocateUserRoles, getAll } from '@/services/role'
import { ID } from '@/types'
import { wrapAsyncWithLoading } from '@/utils/helper'
export default Vue.extend({
  name: 'FormAllocRole',
  props: ['userId'],
  data () {
    return {
      locking: false,
      options: [],
      roles: []
    }
  },
  created () {
    wrapAsyncWithLoading(this, 'locking', ['loadData', 'submit'])
    this.loadData()
  },
  methods: {
    async loadData () {
      await Promise.all([
        getUserRoles(this.userId).then(({ data }) => {
          this.roles = data.data.map(({ id }: { id: ID }) => id)
        }),
        getAll().then(({ data }) => {
          this.options = data.data.map(({ id: value, name: label }: { id: ID; name: string }) => ({ label, value }))
        })
      ]).catch(error => {
        this.$emit('fatal', error)
      })
    },
    async submit () {
      await allocateUserRoles(this.userId, this.roles)
      this.$emit('suc')
    }
  }
})
</script>
